package cn.lili.modules.member.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.PartnerVO;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * create by yudan on 2022/2/18
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements PartnerService {


    public IPage<PartnerVO> getPartnerPage(PartnerVO partner, PageVO page) {
        QueryWrapper<Partner> queryWrapper = Wrappers.query();
        queryWrapper.and(wrapper -> wrapper.isNull("p.partner_state").or().eq("p.partner_state",0));
        queryWrapper.and(wrapper -> wrapper.isNull("p.delete_flag").or().eq("p.delete_flag",0));
        queryWrapper.and(wrapper -> wrapper.isNull("p.end_time").or().gt("p.end_time", new Date()));
        if (partner.getPartnerType() != null) {
            queryWrapper.eq("p.partner_type", partner.getPartnerType());
        }
        if (partner.getMemberId() != null) {
            queryWrapper.eq("m.id", partner.getMemberId());
        }
        queryWrapper.groupBy("m.id,m.promotion_code");
        return this.baseMapper.getPartnerPage(PageUtil.initPage(page), queryWrapper);
    }

    @Override
    public Partner updatePartner(Partner Partner) {
        //判断是否用户登录并且会员ID为当前登录会员ID
        AuthUser tokenUser = UserContext.getCurrentUser();
        if (tokenUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        this.updateById(Partner);
        return Partner;
    }
}
